import json
import re
from time import sleep
from sendWx import send, start_wx
from urllib import parse, request
from http.server import BaseHTTPRequestHandler, HTTPServer

host = ('localhost', 8899)
enc = "UTF-8"  # 设置返回的编码格式
server = None


class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        query = parse.urlparse(self.path)
        self.do_action('{"success":2,"error":"please Use the post method!"}')

    def do_POST(self):
        path = str(self.path)  # 获取请求的url
        length = int(self.headers["Content-length"])
        request_str = self.rfile.read(length).decode(enc)
        query = json.loads(request_str)
        if path == "/sendWx":
            body = send(query['esReceiver'], query['esContent'])
            self.do_action(json.dumps(body))

    def do_action(self, content):
        print(content)
        self.send_response(200)  # 返回状态码
        self.send_header("Content-type", "application/json;charset=%s" % enc)  # 返回响应头内容
        self.end_headers()  # 返回响应头结束
        self.wfile.write(content.encode(enc))  # 发送json格式的返回包体


mode = 1  # 1、服务模式 2、客户端模式


def start_server(hname, port, wx):
    global mode
    if wx == '是':
        start_wx()
    if re.match('http', hname.strip()):
        mode = 2
        start_request(hname, port)
    else:
        mode = 1
        hp = tuple([hname, port]) if hname else host
        global server
        server = HTTPServer(hp, Resquest)
        print("Starting server, listen at: %s:%s" % hp)
        server.serve_forever()


run = True


def start_request(url, interval=120):
    i = 0
    global run
    while run:
        i += 1
        sents = []
        try:
            print('\n第' + str(i) + '次请求开始 ' + url)
            with request.urlopen(url) as f:
                if int(f.status) == 200:
                    res = f.read().decode(enc)
                    print('Data:', res)
                    query = json.loads(res)
                    if int(query['total']):
                        for msg in query['records']:
                            if msg['esContent']:
                                body = send(msg['esReceiver'], msg['esContent'])
                                sents.append(dict(msg, **body))
                        req = request.Request(url)
                        req.add_header('Content-Type','application/json;charset=UTF-8')
                        request.urlopen(req, json.dumps(sents).encode(enc))
        except Exception as err:
            print(str(err))
        sleep(interval)
    print('循环请求退出！')
    run = True


def stop():
    if mode == 1:
        server.shutdown()
    else:
        global run
        run = False
    print('shutdown success!')


if __name__ == '__main__':
    start_server('')
